﻿using System;
using System.Drawing;
using System.Windows.Controls;
using System.Windows.Forms;

namespace PPSkin
{
    public partial class PPMediaPlayer : System.Windows.Forms.UserControl
    {
        private MediaElement mediaElement = new MediaElement();

        private Timer timer = new Timer();
        private Timer ftimer = new Timer();//用来全屏定时

        public PPMediaPlayer()
        {
            InitializeComponent();
            mediaElement.AllowDrop = true;
            mediaElement.DragEnter += new System.Windows.DragEventHandler(mediaElement_DragEnter);
            mediaElement.Drop += new System.Windows.DragEventHandler(mediaElement_Drop);
            mediaElement.MediaOpened += new System.Windows.RoutedEventHandler(mediaElement_MediaOpend);
            mediaElement.MouseMove += new System.Windows.Input.MouseEventHandler(mediaElement_MouseMove);
            elementHost1.Child = mediaElement;
            mediaElement.Visibility = System.Windows.Visibility.Visible;
            timer.Interval = 1000;
            timer.Tick += new EventHandler(Timer_Tick);
            ftimer.Interval = 5000;
            ftimer.Tick += new EventHandler(FTimer_Tick);
            Button_play_pause.Tag = "play";
            ppTrackBar_volume.Value = 50;
            //panel_controls.BackColor = Color.FromArgb(50, panel_controls.BackColor.R, panel_controls.BackColor.G, panel_controls.BackColor.B);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            panel_controls.Size = new Size(this.Width, 48);
            panel_controls.Location = new Point(0, this.Height - 48);
            elementHost1.Location = new Point(0, 0);
            elementHost1.Size = new Size(this.Width, this.Height - panel_controls.Height);

            label_totalTime.Location = new Point(this.Width - label_totalTime.Width, 1);
            label_currentTime.Location = new Point(this.Width - label_totalTime.Width - label_currentTime.Width - 3, 1);
            ppTrackBar1.Size = new Size(this.Width - label_totalTime.Width - label_currentTime.Width - 10, 30);
            ppTrackBar1.Location = new Point(3, -8);

            Button_play_pause.Size = new Size(30, 30);
            Button_stop.Size = new Size(30, 30);
            Button_backward.Size = new Size(30, 30);
            Button_forward.Size = new Size(30, 30);
            Button_fullscreen.Size = new Size(30, 30);
            Button_openfile.Size = new Size(30, 30);

            Button_play_pause.Location = new Point(0, panel_controls.Height - 31);
            Button_stop.Location = new Point(30, panel_controls.Height - 31);
            Button_backward.Location = new Point(60, panel_controls.Height - 31);
            Button_forward.Location = new Point(90, panel_controls.Height - 31);
            Button_fullscreen.Location = new Point(this.Width - 30, panel_controls.Height - 31);
            Button_openfile.Location = new Point(this.Width - 60, panel_controls.Height - 31);

            ppTrackBar_volume.Size = new Size(100, 30);
            ppTrackBar_volume.Location = new Point(Button_openfile.Location.X - 120, 14);
        }

        private void mediaElement_DragEnter(object sender, System.Windows.DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent(DataFormats.Text))
                e.Effects = System.Windows.DragDropEffects.Link;
            else e.Effects = System.Windows.DragDropEffects.None;
        }

        private void mediaElement_Drop(object sender, System.Windows.DragEventArgs e)
        {
            string path = "";
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            }
            else if (e.Data.GetDataPresent(DataFormats.Text))
            {
                path = e.Data.GetData(DataFormats.Text).ToString();
            }

            mediaElement.Language = System.Windows.Markup.XmlLanguage.Empty;

            mediaElement.Source = new Uri(path);
            mediaElement.Play();
            Button_play_pause.Tag = "pause";
            this.Invoke(new MethodInvoker(() => { Button_play_pause.IcoRegular = PPSkinResources.pause; Button_play_pause.IcoIn = PPSkinResources.pause; Button_play_pause.IcoDown = PPSkinResources.pause; }));
            timer.Start();
        }

        public event EventHandler FileOpened;

        public string FilePath = string.Empty;

        private void mediaElement_MediaOpend(object sender, System.Windows.RoutedEventArgs e)
        {
            FilePath = mediaElement.Source.LocalPath;
            TimeSpan ts = mediaElement.NaturalDuration.TimeSpan;
            label_totalTime.Text = ts.Hours.ToString().PadLeft(2, '0') + ":" + ts.Minutes.ToString().PadLeft(2, '0') + ":" + ts.Seconds.ToString().PadLeft(2, '0');
            ppTrackBar1.MaxValue = (int)ts.TotalSeconds;
            if (FileOpened != null)
            {
                FileOpened(this, new EventArgs());
            }
        }

        protected override void OnMouseEnter(EventArgs e)
        {
            base.OnMouseEnter(e);
            panel_controls.Visible = true;
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            if (!this.RectangleToScreen(this.ClientRectangle).Contains(System.Windows.Forms.Control.MousePosition))
            {
                base.OnMouseLeave(e);

                panel_controls.Visible = false;
            }
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            panel_controls.Size = new Size(this.Width, 48);
            panel_controls.Location = new Point(0, this.Height - 48);
            elementHost1.Location = new Point(0, 0);
            elementHost1.Size = new Size(this.Width, this.Height - panel_controls.Height);

            label_totalTime.Location = new Point(this.Width - label_totalTime.Width, 1);
            label_currentTime.Location = new Point(this.Width - label_totalTime.Width - label_currentTime.Width - 3, 1);
            ppTrackBar1.Size = new Size(this.Width - label_totalTime.Width - label_currentTime.Width - 10, 30);
            ppTrackBar1.Location = new Point(3, -8);

            Button_play_pause.Size = new Size(30, 30);
            Button_stop.Size = new Size(30, 30);
            Button_backward.Size = new Size(30, 30);
            Button_forward.Size = new Size(30, 30);
            Button_fullscreen.Size = new Size(30, 30);
            Button_openfile.Size = new Size(30, 30);

            Button_play_pause.Location = new Point(0, panel_controls.Height - 31);
            Button_stop.Location = new Point(30, panel_controls.Height - 31);
            Button_backward.Location = new Point(60, panel_controls.Height - 31);
            Button_forward.Location = new Point(90, panel_controls.Height - 31);
            Button_fullscreen.Location = new Point(this.Width - 30, panel_controls.Height - 31);
            Button_openfile.Location = new Point(this.Width - 60, panel_controls.Height - 31);

            ppTrackBar_volume.Size = new Size(100, 30);
            ppTrackBar_volume.Location = new Point(Button_openfile.Location.X - 120, 14);
        }

        private void Button_openfile_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }

        private void Button_openfile_DragDrop(object sender, DragEventArgs e)
        {
            string path = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
            mediaElement.Source = new Uri(path, UriKind.Absolute);
            mediaElement.LoadedBehavior = MediaState.Manual;
            mediaElement.Play();
            Button_play_pause.Tag = "pause";
            this.Invoke(new MethodInvoker(() => { Button_play_pause.IcoRegular = PPSkinResources.pause; Button_play_pause.IcoIn = PPSkinResources.pause; Button_play_pause.IcoDown = PPSkinResources.pause; }));
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                TimeSpan ts = mediaElement.Position;
                label_currentTime.Text = ts.Hours.ToString().PadLeft(2, '0') + ":" + ts.Minutes.ToString().PadLeft(2, '0') + ":" + ts.Seconds.ToString().PadLeft(2, '0');
                if (ts.TotalSeconds <= ppTrackBar1.MaxValue)
                {
                    ppTrackBar1.Value = (int)ts.TotalSeconds;
                }
            }
            catch { }
        }

        private void trackBar1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                timer.Stop();
            }
        }

        private void trackBar1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                try
                {
                    mediaElement.Position = new TimeSpan(0, 0, (int)ppTrackBar1.Value);
                }
                catch { }
                timer.Start();
            }
        }

        private void ppTrackBar_volume_ValueChanged(object sender, EventArgs e)
        {
            mediaElement.Volume = (double)ppTrackBar_volume.Value / 100;
        }

        private Size defaultSize = new Size();
        private FormBorderStyle defaultStyle = new FormBorderStyle();
        private Point defaultPoint = new Point();
        private Padding defaultPadding = new Padding(0, 0, 0, 0);
        private Rectangle defaultRect = new Rectangle(0, 0, 100, 100);
        private bool isFullscreen = false;

        private void mediaElement_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (isFullscreen)
            {
                Point mousepoint = PointToClient(MousePosition);
                if (mousepoint.Y > (this.Parent as Form).Height - panel_controls.Height && mousepoint.Y < (this.Parent as Form).Height)
                {
                    panel_controls.BringToFront();
                    //ftimer.Stop();
                    //ftimer.Start();
                }
                else
                {
                    panel_controls.SendToBack();
                }
            }
        }

        private void FTimer_Tick(object sender, EventArgs e)
        {
            panel_controls.SendToBack();
        }

        public void FullScreen()
        {
            Rectangle screenRect = Screen.FromHandle(this.Handle).Bounds;
            if (this.Size != screenRect.Size)
            {
                defaultSize = (this.Parent as Form).Size;
                defaultStyle = (this.Parent as Form).FormBorderStyle;
                defaultPoint = (this.Parent as Form).Location;
                defaultPadding = (this.Parent as Form).Padding;
                defaultRect = new Rectangle(this.Location, this.Size);
                (this.Parent as Form).FormBorderStyle = FormBorderStyle.None;
                (this.Parent as Form).Size = screenRect.Size;
                (this.Parent as Form).Left = screenRect.X;
                (this.Parent as Form).Top = screenRect.Y;
                (this.Parent as Form).TopMost = true;
                (this.Parent as Form).Padding = new Padding(0, 0, 0, 0);
                this.Location = new Point(0, 0);
                this.Size = (this.Parent as Form).Size;
                elementHost1.Size = this.Size;
                panel_controls.SendToBack();
                if (mediaElement.Source == null)
                {
                    panel_controls.BringToFront();
                }
                isFullscreen = true;
                Button_fullscreen.IcoRegular = PPSkinResources.Restore;
                Button_fullscreen.IcoIn = PPSkinResources.Restore;
                Button_fullscreen.IcoDown = PPSkinResources.Restore;
            }
        }

        public void unFullScreen()
        {
            Rectangle screenRect = Screen.FromHandle(this.Handle).Bounds;
            if (this.Size == screenRect.Size)
            {
                (this.Parent as Form).FormBorderStyle = defaultStyle;
                (this.Parent as Form).Size = defaultSize;
                (this.Parent as Form).Location = defaultPoint;
                (this.Parent as Form).Padding = defaultPadding;
                this.Location = defaultRect.Location;
                this.Size = defaultRect.Size;
                elementHost1.Size = new Size(this.Width, this.Height - panel_controls.Height);
                panel_controls.BringToFront();
                isFullscreen = false;
                Button_fullscreen.IcoRegular = PPSkinResources.Max;
                Button_fullscreen.IcoIn = PPSkinResources.Max;
                Button_fullscreen.IcoDown = PPSkinResources.Max;
            }
        }

        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            base.OnKeyPress(e);
            if (e.KeyChar == 27)
            {
                unFullScreen();
            }
        }

        private void Button_play_pause_Click(object sender, EventArgs e)
        {
            if ((string)Button_play_pause.Tag == "play")
            {
                if (mediaElement.Source != null)
                {
                    mediaElement.Play();
                    Button_play_pause.Tag = "pause";
                    this.Invoke(new MethodInvoker(() => { Button_play_pause.IcoRegular = PPSkinResources.pause; Button_play_pause.IcoIn = PPSkinResources.pause; Button_play_pause.IcoDown = PPSkinResources.pause; }));
                    timer.Start();
                }
            }
            else
            {
                if (mediaElement.Source != null)
                {
                    mediaElement.Pause();
                    Button_play_pause.Tag = "play";
                    this.Invoke(new MethodInvoker(() => { Button_play_pause.IcoRegular = PPSkinResources.play; Button_play_pause.IcoIn = PPSkinResources.play; Button_play_pause.IcoDown = PPSkinResources.play; }));
                    timer.Stop();
                }
            }
        }

        private void Button_stop_Click(object sender, EventArgs e)
        {
            mediaElement.Stop();
        }

        private void Button_backward_Click(object sender, EventArgs e)
        {
            mediaElement.Position = mediaElement.Position - TimeSpan.FromSeconds(5);
        }

        private void Button_forward_Click(object sender, EventArgs e)
        {
            mediaElement.Position = mediaElement.Position + TimeSpan.FromSeconds(5);
        }

        private void Button_fullscreen_Click(object sender, EventArgs e)
        {
            Rectangle screenRect = Screen.FromHandle(this.Handle).Bounds;
            if (this.Size != screenRect.Size)
            {
                FullScreen();
            }
            else
            {
                unFullScreen();
            }
        }

        private void Button_openfile_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            opf.Filter = "(*.mp4,*.mkv)|*.mp4;*.mkv";
            if (opf.ShowDialog() == DialogResult.OK)
            {
                string filename = opf.FileName;
                try
                {
                    mediaElement.Source = new Uri(filename, UriKind.Absolute);
                    mediaElement.LoadedBehavior = MediaState.Manual;
                    mediaElement.Play();
                    Button_play_pause.Tag = "pause";
                    this.Invoke(new MethodInvoker(() => { Button_play_pause.IcoRegular = PPSkinResources.pause; Button_play_pause.IcoIn = PPSkinResources.pause; Button_play_pause.IcoDown = PPSkinResources.pause; }));
                    timer.Start();
                }
                catch { }
            }
        }
    }
}